/*
 * Copyright 2010 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.client;

import java.util.ArrayList;

import org.shalma.Query;
import org.shalma.Query.FilterOperator;
import org.shalma.client.Callback;
import org.shalma.client.Persistence;
import org.shalma.client.view.View;
import org.shalma.internal.client.SearchOracle.SearchSuggestion;
import org.shalma.internal.reflection.MetaClass;
import org.shalma.internal.reflection.MetaClassRegistry;
import org.shalma.model.Entity;
import org.shalma.model.NamedEntity;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.Widget;

public class SearchView extends View implements
		ValueChangeHandler<SearchSuggestion>, KeyDownHandler {

	interface Binder extends UiBinder<Widget, SearchView> {
	}

	private static final Binder binder = GWT.create(Binder.class);

	@UiField(provided = true)
	SuggestBox suggestBox;

	@UiField(provided = true)
	FlowPanel entityList;

	private SuggestOracle oracle;

	public SearchView() {

		entityList = new FlowPanel();

		oracle = new SearchOracle();
		suggestBox = new SuggestBox(oracle);
		initWidget(binder.createAndBindUi(this));

		suggestBox.getTextBox().addKeyDownHandler(this);

		// suggestBox.addKeyDownHandler(this);
	}

	@Override
	public void onShow() {

		suggestBox.getTextBox().setFocus(true);
		String token = History.getToken();

		if (token.length() > 1)
			search(token.substring(1));
	}

	private void search(String search) {

		entityList.clear();

		MetaClass metaClass = MetaClassRegistry.instance
				.getMetaClassByName(search);

		if (metaClass == null) {
			entityList.add(new Label("Unknow entity: " + search));
		} else {
			entityList.add(new Label("Working"));

			Query<Entity> query = new Query<Entity>(Query.CLASS_PROPERTY,
					FilterOperator.EQUAL, metaClass.getId());

			update(query);
		}
	}

	@Override
	public void onValueChange(ValueChangeEvent<SearchSuggestion> event) {
		// TODO Auto-generated method stub

		// BeanManager.instance.showClass(event.getValue());
	}

	@Override
	public void onKeyDown(KeyDownEvent event) {

		if (KeyCodes.KEY_ENTER == event.getNativeKeyCode()) {

			History.newItem(Shell.SEARCH_TOKEN + suggestBox.getText());

		}
		// && !((DefaultSuggestionDisplay) suggestBox
		// .getSuggestionDisplay()).isSuggestionListShowing()) {
		//
		// entityList.clear();
		// entityList.add(new Label("Working..."));
		//
		// MetaClass bean = MetaClassRegistry.instance.getMetaClass(suggestBox
		// .getText());
		// Query<Entity> query = new Query<Entity>(Query.CLASS_PROPERTY,
		// FilterOperator.EQUAL, bean.getId());
		//
		// update(query);
		// }

		// if (KeyCodes.KEY_ENTER == event.getNativeKeyCode()
		// && !((DefaultSuggestionDisplay) suggestBox
		// .getSuggestionDisplay()).isSuggestionListShowing()) {
		//
		// entityList.clear();
		// entityList.add(new Label("Working..."));
		//
		// MetaClass bean = MetaClassRegistry.instance.getMetaClass(suggestBox
		// .getText());
		// Query<Entity> query = new Query<Entity>(Query.CLASS_PROPERTY,
		// FilterOperator.EQUAL, bean.getId());
		//
		// update(query);
		// }

	}

	public void update(Query<Entity> query) {

		entityList.clear();

		Persistence.instance.get(query, new Callback<ArrayList<Entity>>() {
			@Override
			public void onSuccess(ArrayList<Entity> entities) {
				update(entities);
			}
		});
	}

	void update(ArrayList<Entity> entities) {

		if (entities.isEmpty()) {
			entityList.add(new Label("Empty"));
		} else
			for (Entity entity : entities) {

				String name = (entity instanceof NamedEntity) ? ((NamedEntity) entity)
						.getName() : entity.getId();
				Hyperlink link = new Hyperlink(name, entity.getId());
				entityList.add(link);
			}
	}

	public class SearchSuggestBox extends SuggestBox implements KeyPressHandler {

		public void init() {

		}

		@Override
		public void onKeyPress(KeyPressEvent event) {
			// TODO Auto-generated method stub

		}
	}
}
